package com.chang.rentmall.controllers;

import com.chang.rentmall.beans.MessageBean;
import com.chang.rentmall.utils.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class ImageController {
    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${img.location}")
    private String location;
    @RequestMapping(value = "img/upload")
    public MessageBean uploadImg (@RequestParam("files")MultipartFile multipartFile) {
        MessageBean messageBean = new MessageBean();
        if (multipartFile.isEmpty() || multipartFile.getOriginalFilename().equals("")) {
            messageBean.setMessage("图片名不能为空");
            messageBean.setCode(-1);
            return messageBean;
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            messageBean.setValues(0, "图片格式错误", "");
            return messageBean;
        }
        String root_fileName = multipartFile.getOriginalFilename();
        logger.info("上传图片:name={},type={}", root_fileName, contentType);
        //处理图片
        String return_path = "";
        String filePath = location + return_path;
        logger.info("图片保存路径={}", filePath);
        String file_name = null;
        try {
            file_name = ImageUtil.saveImg(multipartFile, filePath);
            messageBean.setValues(200, "上传成功", return_path+ File.separator+file_name);
            logger.info("返回值：{}", messageBean);
            return messageBean;
        } catch (IOException e) {
            logger.error("上传图片失败", e);
        }
        return messageBean;
    }
}
